import { select, selectAll } from "d3-selection";

export function getSmoothPath(s, e) {
  const offset = 4; // 小直线长度
  const curveOffset = 80; // 控制曲线弯曲程度（可调）

  // 控制点：水平偏移，垂直居中
  const c1x = s.x;
  const c1y = s.y + curveOffset;
  const c2x = e.x;
  const c2y = e.y - curveOffset;

  return `
      M ${s.x} ${s.y}
      L ${s.x} ${s.y + offset}
      C ${c1x} ${c1y} ${c2x} ${c2y} ${e.x} ${e.y - offset}
      L ${e.x} ${e.y}
    `
    .replace(/\s+/g, " ")
    .trim();
}

export function findPortElement(portInfo, viewport) {
  const nodeGroup = viewport
    .selectAll("g")
    .filter(function (d) {
      return d && d.id === portInfo.nodeId;
    })
    .node();

  if (!nodeGroup) return null;

  return select(nodeGroup)
    .selectAll(".port")
    .filter(function () {
      return select(this).attr("data-port") === portInfo.port;
    })
    .node();
}

export function getPortPosition(port, targetSvg, currentTransform) {
  const svg = targetSvg.node();
  const pt = svg.createSVGPoint();
  pt.x = +port.getAttribute("cx");
  pt.y = +port.getAttribute("cy");
  const globalPoint = pt.matrixTransform(port.getCTM());

  // 添加对 currentTransform 的检查
  if (currentTransform) {
    // 将屏幕坐标逆变换为 viewport 内的逻辑坐标
    const logicalX = currentTransform.invertX(globalPoint.x);
    const logicalY = currentTransform.invertY(globalPoint.y);
    return { x: logicalX, y: logicalY };
  } else {
    // 如果 currentTransform 为空，直接返回全局坐标
    return { x: globalPoint.x, y: globalPoint.y };
  }
}

// 更新指定节点的所有连线
export function updateConnections(
  nodeId,
  connections,
  viewport,
  currentTransform,
  targetSvg
) {
  connections.forEach((conn) => {
    if (conn.from.nodeId === nodeId || conn.to.nodeId === nodeId) {
      const sPort = findPortElement(conn.from, viewport);
      const ePort = findPortElement(conn.to, viewport);
      if (sPort && ePort) {
        const s = getPortPosition(sPort, targetSvg, currentTransform);
        const e = getPortPosition(ePort, targetSvg, currentTransform);
        select(conn.path).attr("d", getSmoothPath(s, e));
      }
    }
  });
}

export function drawLine(viewport, s, e, selectedConnection) {
  return viewport
    .insert("path", ":first-child")
    .attr("d", getSmoothPath(s, e))
    .attr("stroke", "#A2B1C3")
    .attr("stroke-width", 2)
    .attr("marker-end", "url(#arrowhead)") // 确保使用正确的marker ID
    .attr("fill", "none")
    .attr("cursor", "pointer")
    .attr("class", "connection-line")
    .on("click", function (event) {
      event.stopPropagation();
      const path = select(this);

      if (selectedConnection && selectedConnection !== this) {
        select(selectedConnection)
          .classed("selected-connection", false)
          .attr("stroke", "#A2B1C3");
      }

      const isSelected = path.classed("selected-connection");
      if (isSelected) {
        path.classed("selected-connection", false).attr("stroke", "#A2B1C3");
        selectedConnection = null;
      } else {
        path.classed("selected-connection", true).attr("stroke", "#239edd");
        selectedConnection = this;
      }
    });
}
